import React, { Component } from 'react'
import { Input, Card, Button, Radio, Form, Row, Col, message, Select } from 'antd'
import { history } from 'umi'
import { connect } from 'dva'

const namespaceClass = 'class'
const namespaceVeifyCode = 'verify_code'
function mapStateToProps (state) {
    const { shcoolClass } = state[namespaceClass]
    let { image } = state[namespaceVeifyCode]
    image =
        "data:image/png;base64," +
        btoa(
            new Uint8Array(image).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ""
            )
        );
    return {
        shcoolClass,
        image
    }
}
function mapDispatchToProps (dispatch) {
    return {
        findAllClass () {
            dispatch({
                type: `${namespaceClass}/findAllClass`
            })
        },
        async getImage () {
            await dispatch({
                type: `${namespaceVeifyCode}/getImage`
            })
        },
        async checkVerifyCode (code) {
            const result = await dispatch({
                type: `${namespaceVeifyCode}/checkVerifyCode`,
                code
            })
            return result
        },
    }
}
class Register extends Component {

    formRef = React.createRef()

    constructor(props) {
        super(props)
        this.state = {
            identity: 'student',
            verifyCodeLoading: false
        }
        this.changeVerifyCode = this.changeVerifyCode.bind(this)
        this.submit = this.submit.bind(this)
    }

    componentDidMount () {
        this.props.findAllClass()
        this.changeVerifyCode()
    }

    async changeVerifyCode () {
        await this.props.getImage()
        this.setState({
            verifyCodeLoading: true
        })
        if (!this.props.image) {
            message.warn('刷新验证码失败，请稍后再次尝试')
        }
        this.setState({
            verifyCodeLoading: false
        })
    }

    async submit () {
        this.setState({
            submitLoading: true
        })
        const { id, password, verifyCode, identity } = this.formRef.current.getFieldsValue()
        const verifyResult = await this.props.checkVerifyCode(verifyCode.toUpperCase())
        if (verifyResult.status === 0) {
            switch (identity) {
                case 'student':{
                    const registerResult = await this.props.studentLogin(id, password)
                    if(registerResult.status === 0){
                        // 跳转
                        history.push('/Login')
                    }else{
                        this.changeVerifyCode()
                        message.error(registerResult.message)
                    }
                    break
                }
                case 'teacher':{
                    const registerResult = await this.props.teacherLogin(id, password)
                    if(registerResult.status === 0){
                        // 跳转
                        history.push('/Login')
                    }else{
                        this.changeVerifyCode()
                        message.error(registerResult.message)
                    }
                    break
                }
                default: console.log(`身份有误：${identity}`)
                    break
            }
        } else {
            message.error(verifyResult.message)
        }
        this.setState({
            submitLoading: false
        })
    }

    render () {
        return <div style={{ width: '100vw', height: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <Card style={{ width: '400px', height: 'auto' }}>
                <div style={{ textAlign: 'center' }} >
                    <h1>注册</h1>
                </div>
                <Form ref={this.formRef} labelAlign='right'>
                    <Form.Item name='id' label='账号：' labelCol={{ span: 6 }}
                        rules={[
                            {
                                required: true,
                                message: '内容不能为空!',
                            },
                        ]}>
                        <Input placeholder='请输入学号或教师工号' />
                    </Form.Item>
                    <Form.Item name='password' label='密码:' labelCol={{ span: 6 }}
                        rules={[
                            {
                                required: true,
                                message: '内容不能为空!',
                            },
                        ]}>
                        <Input placeholder='输入密码'></Input>
                    </Form.Item>
                    <Form.Item name='passwordAgain' label='确认密码:' labelCol={{ span: 6 }}
                        rules={[
                            {
                                required: true,
                                message: '内容不能为空!',
                            },
                        ]}>
                        <Input placeholder='再次输入密码'></Input>
                    </Form.Item>
                    <Form.Item name='schoolClass' label='班级:' labelCol={{ span: 6 }}
                        rules={[
                            {
                                required: true,
                                message: '内容不能为空!',
                            },
                        ]}>
                        <Select placeholder='选择班级' options={this.props.shcoolClass?.map((schoolClass) => {
                            return {
                                key: schoolClass.class_id,
                                value: schoolClass.class_name
                            }
                        })}
                            {...(() => {
                                return this.state.identity === 'student' ? {} : { mode: 'multiple' }
                            })()}>
                        </Select>
                    </Form.Item>
                    <Form.Item rules={[
                        {
                            required: true,
                            message: '内容不能为空!',
                        },
                    ]}
                        name='verifyCode'
                        label='验证码'
                        labelCol={{ span: 6 }}>
                        <Row>
                            <Col span={16}>
                                <Input placeholder='请输入验证码' />
                            </Col>
                            <Col span={8} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                <Button style={{
                                    visibility: 'visible',
                                    width: '90%',
                                    height: '90%',
                                    fontSize: '6px',
                                    border: '0px',
                                    color: '#a0a0a0',
                                    backgroundImage: `url(${this.props.image})`,
                                    backgroundRepeat: 'no-repeat',
                                    backgroundSize: '100% 100%',
                                    cursor: 'pointer'
                                }}
                                    onClick={this.changeVerifyCode}
                                >
                                    {this.state.verifyCodeTip}
                                </Button>
                            </Col>
                        </Row>
                    </Form.Item>
                    <Form.Item name='identity' initialValue='student' >
                        <Radio.Group onChange={(e) => {
                            this.formRef.current.setFieldsValue({
                                schoolClass: undefined
                            })
                            this.setState({
                                identity: e.target.value
                            })
                        }}
                            style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                            <Radio value='student' defaultChecked={true}>学生</Radio>
                            <Radio value='teacher'>教师</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item labelCol={{ span: 0 }}>
                        <Button
                            type='primary'
                            style={{ width: '100%' }}
                            shape='round'
                            size='large'
                            htmlType='submit'
                            onClick={this.submit}
                            loading={this.state.submitLoading}>注册</Button>
                    </Form.Item>
                </Form>
                <Button type='link' style={{ float: 'right' }} onClick={() => {
                    history.push('/Login')
                }}>已有账号？点击登录</Button>
            </Card>
        </div>
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Register)